package de.karlNet.sambamanager.ldapController.commands;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.common.IOUtils;
import net.schmizz.sshj.connection.ConnectionException;
import net.schmizz.sshj.connection.channel.direct.Session;
import net.schmizz.sshj.connection.channel.direct.Session.Command;
import net.schmizz.sshj.transport.TransportException;
import net.schmizz.sshj.userauth.UserAuthException;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;

import de.karlNet.sambamanager.ldapController.exceptions.UnsuccessfullCreationException;

public abstract class SamabaToolSSHCommand extends BaseCommand {
	@Value("${ssh.hostname}")
	private String sshHostname;
	@Value("${ssh.username}")
	private String username;
	@Value("${ssh.password}")
	private String password;
	@Value("${ssh.sambatool.path}")
	private String sambaToolPath;
	@Value("${ssh.port}")
	private int sshPort;

	protected String buildParam(String parameter, String value) {
		String retString = "";
		if (StringUtils.isNotBlank(value)) {
			retString = parameter + value;
		}
		return retString;
	}

	protected void execute(String command, String... parameters) {
		final SSHClient ssh = new SSHClient();
		try {
			// ssh.loadKnownHosts();
			ssh.addHostKeyVerifier("97:e1:cf:04:86:da:f1:da:f8:80:f7:3c:0a:fd:fc:7d");
			ssh.connect(this.sshHostname, this.sshPort);
			ssh.authPassword(this.username, this.password);
			final Session session = ssh.startSession();
			try {
				String cmdString = this.sambaToolPath + " " + command;
				for (String parameter : parameters) {
					if (StringUtils.isNotBlank(parameter)) {
						cmdString += " '" + parameter + "'";
					}
				}
				final Command cmd = session.exec(cmdString);
				String outputOfCmd = IOUtils.readFully(cmd.getInputStream())
						.toString();
				cmd.join(15, TimeUnit.SECONDS);
				if (cmd.getExitStatus() != 0) {
					throw new UnsuccessfullCreationException(outputOfCmd,
							cmd.getExitStatus());
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				session.close();
			}
		} catch (UserAuthException e) {
			e.printStackTrace();
		} catch (TransportException e) {
			e.printStackTrace();
		} catch (ConnectionException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				ssh.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
